import useRequest from '@/utils/request'
import { tansParams, blobValidate } from '@/utils/cj'
import { saveAs } from 'file-saver'
import { ElMessage, ElLoading } from 'element-plus'

const request = useRequest({})
let downloadLoadingInstance: any = null
export function download(
  url: string,
  params: Record<string, any>,
  filename: string,
  config?: Record<string, any>,
) {
  downloadLoadingInstance = ElLoading.service({
    text: '正在下载数据，请稍候',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  return request
    .blob(url, params, {
      transformRequest: [
        (params) => {
          return tansParams(params)
        },
      ],
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      responseType: 'blob',
      ...config,
    })
    .then(async (data) => {
      const isBlob = blobValidate(data)
      if (isBlob) {
        const blob = new Blob([data])
        saveAs(blob, filename)
      } else {
        const resText = await data.text()
        const rspObj = JSON.parse(resText)
        const errMsg = rspObj.msg
        ElMessage.error(errMsg)
      }
      downloadLoadingInstance.close()
    })
    .catch((r) => {
      console.error(r)
      ElMessage.error('下载文件出现错误，请联系管理员！')
      downloadLoadingInstance.close()
    })
}
